<script setup>
import { ref, provide, nextTick, computed } from "vue";
// 地图
import ManageMap from "@/components/maps/ManageMap.vue";
// 水量
import AmountChart from "@/components/charts/AmountChart.vue";
// 水质
import QualityChart from "@/components/charts/QualityChart.vue";
// 基本信息
import BasicInfo from "@/components/display/BasicInfo.vue";
// 考核排名
import RankingChart from "@/components/charts/RankingChart.vue";
// 样式-带边框的矩形
import Panel from "@/components/myParts/Panel.vue";
// 样式-头部
import MyHeader from "@/components/myParts/MyHeader.vue";
// 地区选择器
import AreaOption from "@/components/form/AreaOption.vue";
// 请求数据
import {
  passingService,
  foulContentService,
  pureContentService,
  circulatingContentService,
  foulAmountService,
  pureAmountService,
  circulatingAmountService,
  rankingService,
  basicInfoService,
} from "@/api/country.js";
import { cityGetFactoryAPI } from "@/api/foulFactory.js";
import waterContent from "@/assets/waterContent/content.json";
import { xAxisFormatTime } from "@/utils/format.js";
import { scoketURL } from "@/utils/request.js";
import chinaAddress from "@/assets/address/data_geo.json";

// 其他子页面刷新
const isSonActive = ref(false);
const reload = () => {
  isSonActive.value = false;
  nextTick(() => {
    isSonActive.value = true;
  });
};
provide("reload", reload);
// 水体相关子页面刷新
const isWaterSonActive = ref(false);
const waterReload = () => {
  isWaterSonActive.value = false;
  nextTick(() => {
    isWaterSonActive.value = true;
  });
};

// 事件--地区改变
const countryIds = ref([]);
const mapRef = ref(null);
const areaChange = (area) => {
  let numbers = area.geo.split(" ");
  // 地图变换
  mapRef.value.changeCenter(numbers);
  // 向服务器改变参数
  let areaId = String(area.id);
  countryIds.value.splice(0, countryIds.value.length);
  chinaAddress.some((item) => {
    if (
      String(item.value).slice(0, 4) === areaId &&
      String(item.value).length === 6
    ) {
      countryIds.value.push(String(item.value));
    }
  });
  changeCountryIds(countryIds.value);
  // 重新请求数据
  initData();
};
provide("areaChange", areaChange);

// 请求数据
const currentWater = ref("");
const basicInfo = ref({
  sources: 0,
  foulFactories: 0,
  pressures: 0,
  population: 0,
});
const ranking = ref([]);
const initData = async () => {
  // 请求数据
  const res1 = await passingService(countryIds.value);
  passing.value = res1.data.data;
  const res2 = await foulContentService(countryIds.value);
  foulContent.value = res2.data.data;
  const res3 = await pureContentService(countryIds.value);
  pureContent.value = res3.data.data;
  const res4 = await circulatingContentService(countryIds.value);
  circulatingContent.value = res4.data.data;
  const res5 = await foulAmountService(countryIds.value);
  amount.value.foulAmount = res5.data.data;
  const res6 = await pureAmountService(countryIds.value);
  amount.value.pureAmount = res6.data.data;
  const res7 = await circulatingAmountService(countryIds.value);
  amount.value.circulatingAmount = res7.data.data;
  const res8 = await basicInfoService(countryIds.value);
  let info = res8.data.data;
  const res9 = await rankingService(countryIds.value);
  let rank = res9.data.data;
  const res10 = await cityGetFactoryAPI(countryIds.value);
  let factories = res10.data.data;
  // 格式化数据
  basicInfo.value.sources = info.position.sources.length;
  basicInfo.value.foulFactories = info.position.foulFactories.length;
  basicInfo.value.pressures = info.position.pressures.length;
  basicInfo.value.population = info.population;
  ranking.value.splice(0, ranking.value.length);
  for (let i = 0; i < rank.length; i++) {
    let a = {
      id: rank[i].id,
      mark: rank[i].mark,
    };
    ranking.value.push(a);
  }
  // 数据加载完，展示组件
  reload();
  // 水体切换
  onSwitch(currentWater.value === "" ? "foul" : currentWater.value);
  // 地图上显示水厂位置
  let makers = [];
  for (let i = 0; i < factories.length; i++) {
    makers.push(factories[i].position);
  }
  mapRef.value.addPosition(makers);
};

// 建立WebScoket连接，并向WebScoket发送countryIds作为参数
let ws;
const changeCountryIds = (countryIds) => {
  let jsonStr = JSON.stringify(countryIds);
  ws.send(jsonStr);
};
const shake = () => {
  ws = new WebSocket(scoketURL);
  ws.onopen = function () {
    console.log("建立连接--");
    // let jsonStr = JSON.stringify(countryIds.value);
    // ws.send(jsonStr);
  };
  ws.onmessage = function (event) {
    let data = JSON.parse(event.data);
    switch (data.realKey) {
      case "passing":
        passing.value = data.ans;
        reload();
        break;
      case "foulContent":
        foulContent.value = data.ans;
        if (currentWater.value === "foul") {
          waterReload();
        }
        break;
      case "pureContent":
        pureContent.value = data.ans;
        if (currentWater.value === "pure") {
          waterReload();
        }
        break;
      case "circulatingContent":
        circulatingContent.value = data.ans;
        if (currentWater.value === "circulating") {
          waterReload();
        }
        break;
      case "foulAmount":
        amount.value.foulAmount = data.ans;
        if (currentWater.value === "foul") {
          waterReload();
        }
        break;
      case "pureAmount":
        amount.value.pureAmount = data.ans;
        if (currentWater.value === "pure") {
          waterReload();
        }
        break;
      case "circulatingAmount":
        amount.value.circulatingAmount = data.ans;
        if (currentWater.value === "circulating") {
          waterReload();
        }
        break;
      default:
    }
  };
  // 关闭WebScoket连接
  ws.onclose = function (event) {
    console.log("连接关闭");
  };
  ws.onerror = function (event) {
    console.log("连接错误" + event);
  };
};

// 事件--页面加载
const init = () => {
  // 握手
  shake();
};
init();

// 展示数据
const sortedRanking = computed(() => {
  return ranking.value.sort((a, b) => {
    if (a.mark > b.mark) return -1;
    else if (a.rank < b.rank) return 1;
    else return 0;
  });
});
const passing = ref({
  purePassing: 0.0,
  circulatingPassing: 0.0,
  foulPassing: 0.0,
});
const foulContent = ref({});
const pureContent = ref({});
const circulatingContent = ref({});
const amount = ref({
  foulAmount: {},
  pureAmount: {},
  circulatingAmount: {},
});

// 水体切换
const currentQuality = ref({});
const qualityArr = ref([]);
const currentAmount = ref({});
const amountArr = ref([]);
const buttonColor = (water) => {
  if (water !== currentWater.value) {
    return "rgb(255,255,255)";
  } else if (water === "foul") {
    return "rgb(55,210,212)";
  } else if (water === "pure") {
    return "rgb(25,202,136)";
  } else if (water === "circulating") {
    return "rgb(133,143,248)";
  } else {
    return "rgb(255,255,255)";
  }
};
const textColor = (water) => {
  if (water !== currentWater.value) {
    if (water === "foul") {
      return "rgb(55,210,212)";
    } else if (water === "pure") {
      return "rgb(25,202,136)";
    } else if (water === "circulating") {
      return "rgb(133,143,248)";
    }
  } else {
    return "rgb(255,255,255)";
  }
};

const onSwitch = (water) => {
  currentWater.value = water;
  // 水体切换
  switch (currentWater.value) {
    case "pure":
      currentQuality.value = pureContent.value;
      currentAmount.value = amount.value.pureAmount;
      break;
    case "circulating":
      currentQuality.value = circulatingContent.value;
      currentAmount.value = amount.value.circulatingAmount;
      break;
    default:
      currentQuality.value = foulContent.value;
      currentAmount.value = amount.value.foulAmount;
  }
  // 水质
  let i = 0;
  qualityArr.value.splice(0, qualityArr.value.length);
  for (const key in currentQuality.value) {
    let a = {
      key: key,
      value: currentQuality.value[key],
      name: waterContent[currentWater.value][key]["name"],
    };
    qualityArr.value[i] = a;
    i++;
  }
  // 水量
  let j = 0;
  amountArr.value.splice(0, amountArr.value.length);
  for (const key in currentAmount.value) {
    let timeStr = xAxisFormatTime(key);
    let a = {
      time: timeStr,
      value: currentAmount.value[key],
    };
    amountArr.value[j] = a;
    j++;
  }
  // 获取数据后，重新加载子组件
  waterReload();
};
</script>

<template>
  <el-container class="layout-container">
    <el-header>
      <my-header
        text="管理页面 - 数据总览"
        style="height: 100%; width: 100%"
      ></my-header>
    </el-header>
    <el-main>
      <div id="main">
        <div class="map-form">
          <manage-map :zoom="11" ref="mapRef"></manage-map>
        </div>
        <div class="column">
          <div class="panel">
            <panel :check="'bg1'">
              <div class="sort">
                <div class="sort-item">
                  <el-button
                    :color="buttonColor('foul')"
                    @click="onSwitch('foul')"
                  >
                    <el-space wrap>
                      <el-text
                        :style="'color:' + textColor('foul')"
                        size="large"
                        >污水</el-text
                      >
                      <el-text
                        :style="'color:' + textColor('foul')"
                        size="large"
                      >
                        <el-text
                          :style="'color:' + textColor('foul')"
                          size="small"
                          >达标率</el-text
                        >
                        {{ (passing.foulPassing * 100).toFixed(2) }}%
                      </el-text>
                    </el-space>
                  </el-button>
                </div>
                <div class="sort-item">
                  <el-button
                    :color="buttonColor('pure')"
                    @click="onSwitch('pure')"
                  >
                    <el-space wrap>
                      <el-text
                        :style="'color:' + textColor('pure')"
                        size="large"
                        >净水</el-text
                      >
                      <el-text
                        :style="'color:' + textColor('pure')"
                        size="large"
                      >
                        <el-text
                          :style="'color:' + textColor('pure')"
                          size="small"
                          >达标率</el-text
                        >
                        {{ (passing.purePassing * 100).toFixed(2) }}%
                      </el-text>
                    </el-space>
                  </el-button>
                </div>
                <div class="sort-item">
                  <el-button
                    :color="buttonColor('circulating')"
                    @click="onSwitch('circulating')"
                  >
                    <el-space wrap>
                      <el-text
                        :style="'color:' + textColor('circulating')"
                        size="large"
                        >循环水</el-text
                      >
                      <el-text
                        :style="'color:' + textColor('circulating')"
                        size="large"
                      >
                        <el-text
                          :style="'color:' + textColor('circulating')"
                          size="small"
                          >达标率</el-text
                        >
                        {{ (passing.circulatingPassing * 100).toFixed(2) }}%
                      </el-text>
                    </el-space>
                  </el-button>
                </div>
              </div>
            </panel>
          </div>
          <div class="panel">
            <panel :check="'bg2'">
              <div class="quality-items">
                <span class="panel-title">24h水质</span>
                <quality-chart
                  class="quality-chart"
                  v-for="item in qualityArr"
                  :key="item.key"
                  :typeOf="currentWater"
                  :contentKey="item.key"
                  :contentName="item.name"
                  :contentValue="item.value"
                ></quality-chart>
              </div>
            </panel>
          </div>
          <div class="panel">
            <panel :check="'bg2'">
              <span class="panel-title">24h水量</span>
              <amount-chart
                v-if="isWaterSonActive"
                :amount="amountArr"
              ></amount-chart>
            </panel>
          </div>
        </div>
        <div class="column">
          <div class="panel">
            <panel :check="'bg4'">
              <span class="right-panel-title1">基本信息</span>
              <div style="height: 90%">
                <basic-info
                  v-if="isSonActive"
                  :population="basicInfo.population"
                  :pressures="basicInfo.pressures"
                  :sources="basicInfo.sources"
                  :foulFactories="basicInfo.foulFactories"
                ></basic-info>
              </div>
            </panel>
          </div>
          <div class="panel">
            <panel :check="'bg3'">
              <span class="right-panel-title2">各区（县）考核排名</span>
              <div style="height: 90%">
                <ranking-chart
                  v-if="isSonActive"
                  :ranking="sortedRanking"
                ></ranking-chart>
              </div>
            </panel>
          </div>
        </div>
        <div class="area-choice">
          <area-option></area-option>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
  .el-header {
    background-color: rgba(29, 43, 86, 1);
    display: flex;
    flex-direction: row;
    justify-content: center;
    line-height: 60px;
    font-size: 18px;
    .el-dropdown__box {
      display: flex;
      align-items: center;
      .el-icon {
        color: #999;
        margin-left: 10px;
      }
      &:active,
      &:focus {
        outline: none;
      }
    }
  }
  .el-main {
    padding: 0;
    #main {
      width: 100%;
      height: 100%;
      position: relative;
      .map-form {
        width: 100%;
        height: 100%;
      }
      .column:nth-child(2) {
        position: absolute;
        height: 100%;
        width: 25%;
        // z-index: 1;
        left: 0px;
        top: 0px;
      }
      .column:nth-child(3) {
        position: absolute;
        height: 100%;
        width: 25%;
        // z-index: 1;
        right: 0px;
        top: 0px;
      }
      .column {
        padding: 5px;
        display: flex;
        flex-direction: column;
        .panel {
          height: 32%;
          width: 100%;
          margin-bottom: 5px;
          .panel-title {
            position: absolute;
            top: 2px;
            left: 42%;
            text-align: center;
            color: rgba(241, 241, 241, 1);
            font-size: 17px;
            font-weight: lighter;
            font-style: italic;
          }
          .right-panel-title1 {
            position: absolute;
            top: 15%;
            left: 10%;
            text-align: center;
            color: #fff;
            font-size: 17px;
          }
          .right-panel-title2 {
            text-align: center;
            color: #10fafe;
            font-size: 17px;
          }
          .sort {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
            padding: 8%;
            .sort-item {
              display: flex;
              justify-content: space-around;
            }
          }
          .quality-items {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            padding: 0;
            .quality-chart {
              width: 33%;
              height: 46%;
            }
          }
          .el-button {
            width: 96%;
            height: 36px;
          }
        }
      }
      .area-choice {
        position: absolute;
        left: 25%;
        top: 5px;
        width: 22%;
        height: 6%;
      }
    }
  }
}
</style>